package cn.touna.jss.modules.third.fahai;

import cn.touna.risk.api.contraints.facet.First;
import cn.touna.risk.api.contraints.facet.Second;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.properties.disconf.FaHaiProperties;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.fahai.entity.FaHaiRequestEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 法海接口
 * User: lijie
 * Email:lijiewj51137@touna.cn
 * Date: 2017/7/31
 * Time: 10:25
 */

@Service
public class FaHaiService {
    private static final Logger logger = LogManager.getLogger(FaHaiService.class);


    @Autowired
    private FaHaiProperties fahaiproperties;

    /**
     * 法海风控涉诉接口:全文檢索(模糊查詢)
     *
     * @param entity
     * @return
     */
    @ApiMapping(value = "fahai.fuzzyQuery",desc = "法海.全文检索")
    public Response fuzzyQuery(FaHaiRequestEntity entity) {
        logger.info("REQ 【法海风控涉诉接口:全文检索(模糊查詢)】 fuzzyQuery--> paramMap：{}", entity);
        Response<String> response = new Response<>();
        SortedMap<String, String> arguments = new TreeMap<String, String>();
        try {
            Response validResponse = ValidUtil.valid(entity, Second.class);
            if (validResponse != null)
                return validResponse;
            StringBuffer sb = new StringBuffer();
            sb.append(fahaiproperties.getServer());
            sb.append("authCode=").append(fahaiproperties.getAuthCode());
            sb.append("&q=").append(entity.getQ());
            sb.append(StringUtils.isEmpty(entity.getDatatype())?"":"&datatype="+entity.getDatatype());
            sb.append(StringUtils.isEmpty(entity.getPageno())?"":"&pageno="+entity.getPageno());
            sb.append(StringUtils.isEmpty(entity.getRange())?"":"&range="+entity.getRange());
            String result = HttpUtil.getInstance().get(sb.toString());
            JSONObject json =  JSONObject.parseObject(result);
            String code  = json.getString("code");
            String msg  = json.getString("msg");
            if("s".equals(code)){
                return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC,result);
            }
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,msg,result);
        } catch (Exception e) {
            logger.error("【法海风控涉诉接口:全文检索(模糊查詢)】异常,queryLoan--> paramMap：{}", arguments, e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
    }

    /**
     * 法海风控涉诉接口:企業精確查詢
     *
     * @param entity
     * @return
     */
    @ApiMapping(value="fahai.companyPreciseQuery",desc = "法海.全文检索")
    public Response companyPreciseQuery(FaHaiRequestEntity entity) {
        logger.info("REQ 法海风控涉诉接口:企業精確查詢 companyPreciseQuery--> paramMap：{}", entity);
        Response<String> response = new Response<>();
        SortedMap<String, String> arguments = new TreeMap<String, String>();
        try {
            Response validResponse = ValidUtil.valid(entity, Second.class);
            if (validResponse != null)
                return validResponse;
            StringBuffer sb = new StringBuffer();
            sb.append(fahaiproperties.getServer());
            sb.append("authCode=").append(fahaiproperties.getAuthCode());
            sb.append("&q=pname:").append(entity.getName());
            if(!StringUtils.isEmpty(entity.getStartTime())&&!StringUtils.isEmpty(entity.getEndTime()) ){
                sb.append("@sortTime:").append(entity.getStartTime()).append("-").append(entity.getStartTime());
            }
            sb.append(StringUtils.isEmpty(entity.getDatatype())?"":"&datatype="+entity.getDatatype());
            sb.append(StringUtils.isEmpty(entity.getPageno())?"":"&pageno="+entity.getPageno());
            sb.append(StringUtils.isEmpty(entity.getRange())?"":"&range="+entity.getRange());
            String result = HttpUtil.getInstance().get(sb.toString());
            JSONObject json =  JSONObject.parseObject(result);
            String code  = json.getString("code");
            String msg  = json.getString("msg");
            if("s".equals(code)){
                return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC,result);
            }
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,msg,result);
        } catch (Exception e) {
            logger.error("法海风控涉诉接口:企業精確查詢 异常,companyPreciseQuery--> paramMap：{}", arguments, e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
    }

    /**
     * 法海风控涉诉接口:個人精確查詢
     *
     * @param entity
     * @return
     */
    @ApiMapping(value="fahai.personPreciseQuery",desc = "法海.个人精确查询")
    public Response personPreciseQuery(FaHaiRequestEntity entity) {
        logger.info("REQ 法海风控涉诉接口:個人精確查詢 personPreciseQuery--> paramMap：{}", entity);
        Response response = new Response();
        SortedMap<String, String> arguments = new TreeMap<String, String>();
        try {
            Response validResponse = ValidUtil.valid(entity, First.class);
            if (validResponse != null)
                return validResponse;
            StringBuffer sb = new StringBuffer();
            sb.append(fahaiproperties.getPersonServer());
            sb.append("authCode=").append(fahaiproperties.getAuthCode());
            sb.append("&pname=").append(entity.getName());
            sb.append("&idcardNo=").append(entity.getIdCard());
            sb.append(StringUtils.isEmpty(entity.getDatatype())?"":"&datatype="+entity.getDatatype());
            String result = HttpUtil.getInstance().get(sb.toString());
            JSONObject json =  JSONObject.parseObject(result);
            String code  = json.getString("code");
            if("s".equals(code)){
                return response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC,result);
            }
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,result);
        } catch (Exception e) {
            logger.error("法海风控涉诉接口:個人精確查詢 异常,personPreciseQuery--> paramMap：{}", arguments, e);
            return response.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
    }

}
